#!/usr/bin/env bash
# 实例文件：oodiff
# oodiff -- 显示二个OpenOffice/LibreOffice文件内容之间的差异
# 仅适用于.odt文件
#
function usagexit ()
{
    echo "usage: ${0##*/} file1 file2"
    echo "where both files must be .odt files"
    exit $1
} >&2

if (( $# != 2 ))
then
    usagexit 1
fi
if [[ $1 != *.odt || $2 != *.odt ]]
then
    usagexit 2
fi
if [[ ! -r $1 || ! -r $2 ]]
then
    usagexit 3
fi

BAS1=$(basename "$1" .odt)
BAS2=$(basename "$2" .odt)

PRIV1="/tmp/${BAS1}.$$_1"
PRIV2="/tmp/${BAS1}.$$_2"

HERE=$PWD

if [[ ${1:0:1} == '/' ]]
then
    FULL1="${1}"
else
    FULL1="$HERE/${1}"
fi

if [[ ${2:0:1} == '/' ]]
then
    FULL2="${2}"
else
    FULL2="$HERE/${2}"
fi

mkdir "$PRIV1" || { echo "Unable to mkdir "$PRIV1"; exit 4;}
mkdir "$PRIV2" || { echo "Unable to mkdir "$PRIV2"; exit 5;}

cd "$PRIV1"
unzip -q "$FULL1"
sed -e 's/>/>\
/g' -e 's/</\
</g' content.xml > contentwnl.xml

cd "$PRIV2"
unzip -q "$FULL2"
sed -e 's/>/>\
/g' -e 's/</\
</g' content.xml > contentwnl.xml

cd "$HERE"

diff "${PRIV1}/contentwnl.xml" "${PRIV2}/contentwnl.xml"

rm -rf "${PRIV1}" "${PRIV2}"
